import { Injectable, Injector } from '@angular/core';
import { ComponentPortal, ComponentType } from '@angular/cdk/portal';
import { Overlay, OverlayConfig, OverlayRef } from '@angular/cdk/overlay';

@Injectable({
  providedIn: 'root',
})
export class OverlayService {

  constructor(
      private overlay: Overlay,
  ) {
  }

  createPanel(component: ComponentType<any>, left: string, top: string) {
    let strategy = this.overlay.position().global().left(left).top(top);
    let overlayConfig = new OverlayConfig({hasBackdrop: false, positionStrategy: strategy});
    let overlayRef = this.overlay.create(overlayConfig);
    let injector = Injector.create({providers: [{provide: OverlayRef, useValue: overlayRef}]});
    overlayRef.attach(new ComponentPortal(component, null, injector));
  }

  createCenterPanel(component: ComponentType<any>) {
    let strategy = this.overlay.position().global().centerHorizontally().centerVertically();
    let overlayConfig = new OverlayConfig({hasBackdrop: false, positionStrategy: strategy});
    let overlayRef = this.overlay.create(overlayConfig);
    let injector = Injector.create({providers: [{provide: OverlayRef, useValue: overlayRef}]});
    overlayRef.attach(new ComponentPortal(component, null, injector));
  }

  createMask(component: ComponentType<any>) {
    let strategy = this.overlay.position().global().centerHorizontally().centerVertically();
    let overlayConfig = new OverlayConfig({
      hasBackdrop: true,
      backdropClass: ['cdk-overlay-backdrop-transition'],
      positionStrategy: strategy,
    });
    let overlayRef = this.overlay.create(overlayConfig);
    let injector = Injector.create({providers: [{provide: OverlayRef, useValue: overlayRef}]});
    overlayRef.attach(new ComponentPortal(component, null, injector));
  }

  createMessage(component: ComponentType<any>, data: any) {
    let strategy = this.overlay.position().global().centerHorizontally().centerVertically();
    let overlayConfig = new OverlayConfig({hasBackdrop: false, positionStrategy: strategy});
    let overlayRef = this.overlay.create(overlayConfig);
    let injector = Injector.create({
      providers: [
        {provide: OverlayRef, useValue: overlayRef},
        {provide: 'overlay-component-info-message-data', useValue: data}],
    });
    overlayRef.attach(new ComponentPortal(component, null, injector));
  }

  createMouseHoverPanel(component: ComponentType<any>, $event: MouseEvent) {
    let strategy = this.overlay.position().global().left($event.clientX + 'px').top($event.clientY + 'px');
    let overlayConfig = new OverlayConfig({hasBackdrop: false, positionStrategy: strategy});
    let overlayRef = this.overlay.create(overlayConfig);
    let injector = Injector.create({providers: [{provide: OverlayRef, useValue: overlayRef}]});
    overlayRef.attach(new ComponentPortal(component, null, injector));
  }
}
